# -*- coding: utf-8 -*-
from decimal import Decimal
from models.product import Product, attributesCode as attributes
from service.models import Prices
from settings import db

class Catalog():
    products = {}

    def __init__(self, attributes_code=None, entitys_id=None):
        if attributes_code:
            self.attributes_code = attributes_code
            self.setAllProducts(attributes_code, entitys_id)
        else:
            self.attributes_code = attributes

    def setAllProducts(self, attributes_code, entitys_id=None):
        for attribute_code in attributes_code:
            values = self.valueAttribute(attribute_code, entitys_id)
            if values:
                for key in values.keys():
                    if self.products.has_key(key):
                        product = self.products[key]
                        product.setAttrByName(attribute_code, values[key])
                    else:
                        product = Product()
                        product.setAttrByName(attribute_code, values[key])
                    product.entity_id = key
                    self.products[key] = product

    def valueAttribute(self, attribute_code, entitys_id=None):
        result = db.sqlQuery(
            'SELECT attribute_id, backend_type, frontend_input, source_model FROM firsteav_attribute where attribute_code=\'%s\' and entity_type_id=4' % attribute_code)
        if entitys_id:
            if (result[0][2] == 'select' or result[0][2] == 'multiselect') and (
                result[0][3] != 'catalog/product_status'):
                products = db.sqlQuery("""SELECT value,entity_id  FROM firstcatalog_product_entity_int where entity_type_id=4
                and attribute_id=%s and value!='Null' and firstcatalog_product_entity_int.entity_id in %s""" % (
                    result[0][0], str(entitys_id).replace('[', '(').replace(']', ')')))
                productsValue = {}
                for product in products:
                    if product:
                        productValue = db.sqlQuery(
                            'SELECT value FROM firsteav_attribute_option_value where option_id = %s' % product[
                                                                                                               0])
                        if productValue:
                            productsValue[product[1]] = productValue[0][0]
                return productsValue
            else:
                products = db.sqlQuery("""SELECT value, entity_id FROM firstcatalog_product_entity_%s
                    where attribute_id=%s and entity_id in%s""" % (
                    result[0][1], result[0][0], str(entitys_id).replace('[', '(').replace(']', ')')))
        else:
            if (result[0][2] == 'select' or result[0][2] == 'multiselect') and (
                result[0][3] != 'catalog/product_status'):
                products = db.sqlQuery(
                    """SELECT value,entity_id  FROM firstcatalog_product_entity_int where entity_type_id=4 and attribute_id=%s and value!='Null'""" %
                    result[0][0])
                productsValue = {}
                for product in products:
                    if product:
                        productValue = db.sqlQuery(
                            'SELECT value FROM firsteav_attribute_option_value where option_id = %s' % product[
                                                                                                               0])
                        if productValue:
                            productsValue[product[1]] = productValue[0][0]
                return productsValue
            else:
                products = db.sqlQuery("""SELECT value, entity_id FROM firstcatalog_product_entity_%s
                    where attribute_id=%s""" % (result[0][1], result[0][0]))
        productsValue = {}
        for product in products:
            if product:
                if result[0][2] == 'select' and (result[0][3] == 'catalog/product_status'):
                    productsValue[product[1]] = 1 if product[0] == 2 else 0
                else:
                    productsValue[product[1]] = product[0]
        return productsValue

    def filtrProducts(self, filtr=None):
        productsEntity = self.getfiltrProductsEntity(filtr)
        self.setAllProducts(self.attributes_code, productsEntity)

    def getfiltrProductsEntity(self, filt=None):
        productsPrice = Prices.objects.all()
        if filt:
            if filt.has_key('name'):
                if filt['name']:
                    productsPrice = productsPrice.filter(name__contains=filt['name'].encode('utf-8').lower())
            if filt.has_key('price'):
                if filt['price'].isdigit():
                    productsPrice = productsPrice.filter(price=Decimal(filt['price']))
            if filt.has_key('priceFrom'):
                if filt['priceFrom'].isdigit():
                    productsPrice = productsPrice.filter(priceFrom__gt=Decimal(filt['priceFrom']))
            if filt.has_key('priceTo'):
                if filt['priceTo'].isdigit():
                    productsPrice = productsPrice.filter(priceTo__lt=Decimal(filt['priceTo']))
            if filt.has_key('priceAvg'):
                if filt['priceAvg'].isdigit():
                    productsPrice = productsPrice.filter(priceAvg=Decimal(filt['priceAvg']))
            if filt.has_key('status'):
                if filt['status']:
                    status = 1 if filt['status'].encode('utf-8') == 'включен' else 0
                    productsPrice = productsPrice.filter(status=status)
            if filt.has_key('special_price'):
                if filt['special_price']:
                    status = 0 if filt['special_price'].encode('utf-8') == 'Да' else 1
                    productsPrice = productsPrice.filter(special_price=status)
            if filt.has_key('owner'):
                if filt['owner']:
                    productsPrice = productsPrice.filter(owner=filt['owner'])
            if filt.has_key('sort'):
                sort = '' if not filt.has_key('sorting') else filt['sorting']
                productsPrice = productsPrice.order_by(sort + filt['sort'].encode('utf-8'))
        products = []
        for productPrice in productsPrice:
            products.append(int(productPrice.entity_id))
        return products

    def addNewProduct(self, product):
        self.products[product.getSku] = product

